<template>
  <div class="invite-dialog-wrapper">
    <el-dialog
      v-model="visible"
      class="invite-dialog"
      title="靶向班"
      @close="cancelUpdate"
    >
      <div>
        <p class="title">添加可见教师</p>
        <div class="input-container">
          <el-input
            id="inputBox"
            v-model="searchVal"
            placeholder="请输入姓名或账号"
            :prefix-icon="Search"
            @keydown="onKeyDown"
            @focus="getList"
          />
          <ul class="drop-down-list" v-if="searchList.length">
            <li
              class="item"
              v-for="item in searchList"
              :key="item.teacher_id"
              @click="selectTeacher(item)"
            >
              {{ item.name }}
            </li>
          </ul>
        </div>
      </div>
      <div>
        <p class="title">
          当前可见教师<span class="num">（{{ selectedList.length }}）</span>
        </p>
        <p class="selected-box">
          <label v-for="(item, index) in selectedList" :key="index"
            >{{ item.name }}
            <el-icon class="remove-icon" @click="removeStudent">
              <Close /> </el-icon
          ></label>
        </p>
      </div>
      <p class="btn-box">
        <button class="btn cancel" @click="cancelUpdate">取消</button>
        <button class="btn confirm" @click="confirmUpdate">确认</button>
      </p>
    </el-dialog>
  </div>
</template>
<script setup>
import { Close, Search } from '@element-plus/icons-vue'
import {
  searchTeacher,
  updateTargetTeacher
} from '@/apis/class-manage/index.js'
import { debounce } from '@/utils/debounce.js'
import { useAuthStore } from '@/stores'
import { ElMessage } from 'element-plus'
import { ref, watch, nextTick } from 'vue'

const props = defineProps({
  classId: {
    default: '',
    type: String
  },
  list: {
    default: () => [],
    type: Array
  }
})

const emits = defineEmits(['update-list'])
const authStore = useAuthStore()
const visible = defineModel()
const selectedList = ref([])
const removeStudent = index => {
  selectedList.value.splice(index, 1)
}

const searchList = ref([])
const searchVal = ref('')
const getList = async () => {
  const { data } = await searchTeacher({
    school_id: authStore.userInfo.school_id,
    keyword: searchVal.value
  })
  searchList.value = data || []
}

const selectTeacher = teacher => {
  const index = selectedList.value.find(
    item => Number(item.teacher_id) === teacher.teacher_id
  )
  if (index) {
    ElMessage.warning('该教师已添加，请勿重复添加！')
    return
  } else {
    selectedList.value.push(teacher)
  }
  searchList.value = []
}

const onKeyDown = event => {
  if (event.key === 'Enter') getList()
}

watch(
  () => searchVal.value,
  () => {
    debounce(() => {
      getList()
    }, 500)
  }
)

const confirmUpdate = async () => {
  await updateTargetTeacher({
    class_id: +props.classId,
    visible_teacher_id: selectedList.value.map(item => +item.teacher_id)
  })
  ElMessage.success('添加成功')
  emits('confirm-update')
  cancelUpdate()
}

const cancelUpdate = () => {
  selectedList.value = []
  searchList.value = []
  visible.value = false
}

const handleClick = event => {
  const inputBox = document.getElementById('inputBox')
  if (!inputBox?.contains(event.target)) {
    searchList.value = []
  }
}

watch(
  () => visible.value,
  val => {
    if (val) {
      nextTick(() => {
        document.addEventListener('click', handleClick)
      })

      selectedList.value = props.list.map(item => {
        return {
          name: item.teacher_name,
          ...item
        }
      })
    } else {
      document.removeEventListener('click', handleClick)
    }
  }
)
</script>
<style lang="less" scoped>
.invite-dialog-wrapper {
  :deep(.invite-dialog) {
    width: 670px;

    .el-dialog__header {
      font-size: 22px;
      font-weight: 700;
      color: #040b1acc;
    }

    .el-dialog__body {
      display: flex;
      flex-direction: column;
      gap: 20px;
    }

    .input-container {
      position: relative;

      .el-input {
        &__wrapper {
          height: 40px;
          box-shadow: unset;
          border: 1px solid #94bfff;
          border-radius: 5px;
        }
      }

      .drop-down-list {
        width: calc(100% - 16px);
        max-height: 40vh;
        overflow: hidden scroll;
        position: absolute;
        left: 0;
        top: 46px;
        z-index: 1;
        background-color: #fff;
        padding: 8px;
        box-shadow:
          0 8px 24px 0 rgba(4, 11, 25, 0.08),
          0 4px 12px 0 rgba(4, 11, 25, 0.04),
          0 0 1px 0 #d5ddec;

        &::-webkit-scrollbar {
          display: none;
        }

        .item {
          width: 100%;
          height: 36px;
          border-radius: 5px;
          font-size: 16px;
          color: #040b1a;
          text-align: center;
          line-height: 36px;
          cursor: pointer;

          &:hover {
            background: #f5f7fa;
          }
        }
      }
    }

    .selected-box {
      display: flex;
      flex-wrap: wrap;
      gap: 15px;

      label {
        display: inline-flex;
        align-items: center;
        border: 1px solid #9bc3ff;
        color: #9bc3ff;
        padding: 4px 10px;
        border-radius: 3px;
        gap: 20px;

        .close-icon {
          cursor: pointer;
        }
      }
    }

    .title {
      font-size: 18px;
      font-weight: 500;
      margin-bottom: 8px;
      color: rgba(4, 11, 26, 0.9);

      .num {
        color: @color-brand-regular;
      }
    }

    .remove-icon {
      cursor: pointer;
    }

    .btn-box {
      text-align: center;

      .btn {
        cursor: pointer;
        margin-left: 20px;
        background-color: #fff;
        border: 1px solid @color-brand-regular;
        border-radius: 3px;
        font-size: 16px;
        font-weight: 700;
        padding: 7px 20px;
      }

      .confirm {
        background-color: @color-brand-regular;
        color: #fff;
      }

      .cancel {
        color: @color-brand-regular;

        &:hover {
          background-color: #ecf5ff;
        }
      }
    }
  }
}
</style>
